package edu.ynu.se.xiecheng.achitectureclass.service;

import edu.ynu.se.xiecheng.achitectureclass.common.service.LogicService;
import edu.ynu.se.xiecheng.achitectureclass.dao.SoilTemperatureDao;
import edu.ynu.se.xiecheng.achitectureclass.dto.DataDTO;
import edu.ynu.se.xiecheng.achitectureclass.entity.AirTemperature;
import edu.ynu.se.xiecheng.achitectureclass.entity.Device;
import edu.ynu.se.xiecheng.achitectureclass.entity.SoilTemperature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

@Service
public class SoilTemperatureService extends LogicService<SoilTemperatureDao, SoilTemperature, Long> {
    public SoilTemperatureService(@Autowired SoilTemperatureDao dao) { super(dao);}

    @Transactional
    public void SaveData(String name, Double Data, Device device) {
        SoilTemperature soilTemperature = new SoilTemperature();
        soilTemperature.setName(name);
        soilTemperature.setData(Data);
        soilTemperature.setDevice(device);
        dao.save(soilTemperature);
    }
    @Transactional
    public Double getLatestData() {
        List<SoilTemperature> soilTemperatures = dao.findAll(Sort.by(Sort.Direction.DESC, "id"));
        SoilTemperature latest = soilTemperatures.get(0);
        return latest.getData();
    }

    @Transactional
    public List<DataDTO> get7Data() {
        List<SoilTemperature> allSoilTemperatures = dao.findAll(Sort.by(Sort.Direction.DESC, "id"));
        List<DataDTO> dataDTOS = new ArrayList<>();
        List<SoilTemperature> soilTemperatures = new ArrayList<>(allSoilTemperatures.subList(0, Math.min(allSoilTemperatures.size(), 7)));
        for (SoilTemperature soilTemperature : soilTemperatures) {
            DataDTO dataDTO = new DataDTO();
            dataDTO.setData(soilTemperature.getData());
            dataDTO.setGetTime(soilTemperature.getCreateTime());
            dataDTOS.add(dataDTO);
        }
        return dataDTOS;
    }
}
